<template>
  <div class="app-container">

    <!-- 表头 查询与新增 -->
    <el-row>
      <el-col :span="24">
        <div class="filter-container">
          <el-input
            v-model="listQuery.query"
            placeholder="关键词过滤"
            style="width: 200px;"
            class="filter-item"
            @keyup.enter.native="handleFilter"/>
          <el-select
            v-model="listQuery.validFlag"
            placeholder="有效标志"
            clearable
            class="filter-item"
            style="width: 150px"
            @change="handleFilter">
            <el-option v-for="(value, key) in statusOptions" :key="key" :label="value" :value="key"/>
          </el-select>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索
          </el-button>
          <el-button
            class="filter-item"
            style="margin-left: 10px;"
            type="primary"
            icon="el-icon-circle-plus-outline"
            @click="handleCreate">新增
          </el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 表格list -->
    <el-row>
      <el-col :span="24" :gutter="24">
        <el-table
          v-loading="listLoading"
          :key="tableKey"
          :data="list"
          :height="tableHeight"
          element-loading-text="Loading"
          border
          fit
          style="width: 100%;"
          highlight-current-row>
          <el-table-column align="center" label="序号" width="80">
            <template slot-scope="scope">
              {{ scope.$index }}
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="雇员名称" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.empName }}
            </template>
          </el-table-column>
          <!--<el-table-column show-overflow-tooltip label="雇员密码" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.empPw }}
            </template>
          </el-table-column>-->
          <!--<el-table-column show-overflow-tooltip label="角色类型" show-overflow-tooltip style="width: 10%" align="center">-->
          <!--<template slot-scope="scope">-->
          <!--{{ scope.row.roleType | roleFilter(roleOptions)}}-->
          <!--</template>-->
          <!--</el-table-column>-->
          <el-table-column show-overflow-tooltip label="关联门店" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.shopId | shopFilter(shopOptions) }}
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip class-name="status-col" label="有效标志" style="width: 10%" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.validFlag | statusFilter">{{ scope.row.validFlag | validFilter }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleUpdate(scope.row)">
                编辑
              </el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <!-- 分页控件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      layout="total, sizes, prev, pager, next"
      style="float:right;"
      @pagination="fetchData"/>

    <!-- 编辑弹窗 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="100px"
        style="">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="雇员名称" label-width="105px" prop="empName">
              <el-input v-model="temp.empName" :disabled="dialogStatus === 'update'"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="雇员密码" label-width="105px" prop="empPw">
              <el-input v-model="temp.empPw"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色" size="mini" prop="roleIdList">
              <el-checkbox-group v-model="temp.roleIdList">
                <el-checkbox v-for="role in roleList" :key="role.id" :label="role.id">{{ role.roleName }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="关联门店" label-width="105px" prop="shopId">
              <el-select v-model="temp.shopId" class="filter-item" placeholder="请选择关联门店" filterable >
                <el-option
                  v-for="{shopId, shopName} in shopOptions"
                  :key="shopId"
                  :label="shopName"
                  :value="shopId"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12"/>
          <el-col :span="12"/>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="有效标志" label-width="105px">
              <el-switch
                v-model="validSwitch"
                active-color="#13ce66"
                inactive-color="#ff4949"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确认</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import SxEmployeeInfoApi from '@/api/manage/SxEmpManageApi'
  import SxRoleApi from '@/api/manage/SxRoleApi'
  import SxShopInfoApi from '@/api/manage/SxShopInfoApi'
  import waves from '@/directive/waves' // Waves directive
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
  export default {
    directives: { waves },
    components: { Pagination },
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          2: 'gray',
          0: 'danger'
        }
        return statusMap[status]
      },
      validFilter(status) {
        const statusMap = {
          1: '有效',
          0: '作废'
        }
        return statusMap[status]
      },
      roleFilter(status, roleOptions) {
        return roleOptions[status]
      },
      shopFilter(id, shopOptions) {
        const tempArr = shopOptions.filter(item => item.shopId === id)
        if (tempArr.length > 0) {
          return tempArr[0].shopName
        } else {
          return ''
        }
      },
      timeFilter(time) {
        if (time) {
          return new Date(time).Format('yyyy-MM-dd hh:mm:ss')
        } else {
          return ''
        }
      }
    },
    data() {
      return {
        tableKey: 0, // 表格key值
        list: null, // 表格对象
        listLoading: true, // 表格加载框
        total: 0, // 分页总数
        tableHeight: window.innerHeight - 220, // 表格高度
        listQuery: { // 表格查询对象
          pageNum: 1,
          pageSize: 10,
          query: '',
          validFlag: undefined,
          roleType: ''
        },
        temp: {
          empId: '',
          empName: '',
          empPw: '',
          roleType: '',
          menuAuth: '',
          createdTime: '',
          modifiedTime: '',
          validFlag: '1',
          roleIdList: []
        }, // 编辑框临时变量
        roleOptions: {
          9: '超级管理员',
          1: '修片师',
          2: '门店用户'
        },
        shopOptions: [], // 商家数据
        statusOptions: { // 有效无效下拉框
          '1': '有效',
          '0': '作废'
        },
        dialogFormVisible: false, // 编辑框显示
        dialogStatus: '', // 编辑框更新插入状态
        textMap: { // 编辑框标题
          update: '编辑',
          create: '创建'
        },
        rules: { // 编辑框校验规则
          empName: [{ required: true, message: '请输入雇员名称', trigger: 'change' }],
          empPw: [{ required: true, message: '请输入雇员密码', trigger: 'change' }],
          roleType: [{ required: true, message: '请输入角色类型', trigger: 'change' }],
          validFlag: [{ required: true, message: '请输入有效标志', trigger: 'change' }]
        },
        roleList: []
      }
    },
    computed: {
      validSwitch: {
        // getter
        get: function() {
          return this.temp.validFlag === '1'
        },
        // setter
        set: function(newValue) {
          if (newValue) {
            this.temp.validFlag = '1'
          } else {
            this.temp.validFlag = '0'
          }
        }
      }
    },
    created() {
      this.fetchData()
      this.getRoleList()
    },
    methods: {
      getRoleList() {
        SxRoleApi.select({}).then(data => {
          this.roleList = data
        })
      },
      /**
       * 获取表格数据
       */
      fetchData() {
        const that = this
        this.listLoading = true
        this.$http.all([SxEmployeeInfoApi.getPage(this.listQuery), SxShopInfoApi.getList({ validFlag: '1' })])
          .then(this.$http.spread(function(perms, two) {
            that.list = perms.rows
            that.total = perms.total
            that.shopOptions = [{ shopId: '1', shopName: '所有门店' }].concat(two)
            that.listLoading = false
          }))
      },
      /**
       * 新增弹窗
       */
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      /**
       * 清空弹窗内容
       */
      resetTemp() {
        this.temp = {
          empId: '',
          empName: '',
          empPw: '',
          roleType: '',
          menuAuth: '',
          createdTime: '',
          modifiedTime: '',
          validFlag: '1',
          roleIdList: []
        }
      },
      /**
       * 确定新增
       */
      createData() {
        const that = this
        debugger
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            SxEmployeeInfoApi.insert(this.temp).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 1000,
                onClose() {
                  that.fetchData()
                }
              })
            })
          }
        })
      },
      /**
       * 编辑弹窗
       */
      handleUpdate(row) {
        SxEmployeeInfoApi.get(row).then(data => {
          this.temp = Object.assign({}, data)
          this.dialogStatus = 'update'
          this.dialogFormVisible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
        })
      },
      /**
       * 确认编辑
       */
      updateData() {
        const that = this
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            SxEmployeeInfoApi.update(tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 1000,
                onClose() {
                  that.fetchData()
                }
              })
            })
          }
        })
      },
      /**
       * 删除操作
       */
      handleDelete(row) {
        const that = this
        SxEmployeeInfoApi.remove({ empId: row.empId }).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 1000,
            onClose() {
              that.fetchData()
            }
          })
        })
      },
      /**
       * 搜索过滤
       */
      handleFilter() {
        this.listQuery.pageNum = 1
        this.fetchData()
      }
    }
  }
</script>
